from celery.utils.collections import OrderedDict
from django.contrib.auth import logout
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
from django.urls import reverse
from django.views import View
import json
from django import http
import re


from apps.contents.models import ContentCategory
from apps.contents.utils import get_categories
from apps.goods.models import GoodsChannel
from apps.users.utils import generate_verify_email_url, check_verify_email_token
from apps.views import logger
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin



class IndexView(View):
    """首页广告"""

    def get(self, request):
        """提供首页广告界面"""
        # 查询商品频道和分类
        # categories = OrderedDict()
        # channels = GoodsChannel.objects.order_by('group_id', 'sequence')
        # for channel in channels:
        #     group_id = channel.group_id  # 当前组
        #
        #     if group_id not in categories:
        #         categories[group_id] = {'channels': [], 'sub_cats': []}
        #
        #     cat1 = channel.category  # 当前频道的类别
        #
        #     # 追加当前频道
        #     categories[group_id]['channels'].append({
        #         'id': cat1.id,
        #         'name': cat1.name,
        #         'url': channel.url
        #     })
        #     # 构建当前类别的子类别
        #     for cat2 in cat1.subs.all():
        #         cat2.sub_cats = []
        #         for cat3 in cat2.subs.all():
        #             cat2.sub_cats.append(cat3)
        #         categories[group_id]['sub_cats'].append(cat2)
        #
        # # 渲染模板的上下文
        # context = {
        #     'categories': categories,
        # }
        # return render(request, 'index.html', context)
        categories = get_categories()

        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        # 渲染模板的上下文
        context = {
            'categories': categories,
            'contents': contents,
        }
        return render(request, 'index.html', context)


class LogoutView(View):

    def get(self, request):
        """实现退出登录逻辑"""
        # 清理session
        logout(request)
        # 退出登录，重定向到登录页
        response = redirect(reverse('contents:index'))
        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response


class UserInfoView(LoginRequiredMixin, View):
    """用户中心"""

    def get(self, request):
        """提供个人信息界面"""
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return render(request, 'user_center_info.html', context= context)


class EmailView(LoginRequiredJSONMixin, View):
    """ 添加邮箱"""

    def put(self, request):
        # 接收
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')
        # 校验
        if not email:
            return http.HttpResponseBadRequest('缺少email参数')
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseBadRequest('email格式错误')
        # subject
        # 邮件标题
        # message
        # 普通邮件正文，普通字符串
        # from_email
        # 发件人
        # recipient_list
        # 收件人列表
        # html_message
        # 多媒体邮件正文，可以是html字符串
        # send_mail(subject='美多商城',
        #           message='点我啊',
        #           from_email='美多商城<qi_rui_hua@163.com>',
        #           recipient_list=[email],
        #           html_message=None)
        # 赋值
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})

        from celery_tasks.email.tasks import send_verify_email

        verify_url = generate_verify_email_url(request.user)
        send_verify_email.delay(email, verify_url)

        # 返回响应
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'添加邮箱成功'})


class VerifyEmailView(View):
    # 验证邮箱
    def get(self,request):
        # 实现邮箱验证逻辑
        # 接收数据
        token = request.GET.get('token')
        #　验证数据
        if not token:
            return http.HttpResponseBadRequest('缺少token')
        user = check_verify_email_token(token)
        if not user:
            return http.HttpResponseBadRequest('无效的token')

        # 修改email_active的值为True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseBadRequest('验证失败')

        return redirect(reverse('contents:userinfo'))


